package com.zzusedating.androidapp.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zzusedating.androidapp.R;
import com.zzusedating.androidapp.SpecSearchActivity;
import com.zzusedating.androidapp.adapters.RecommendRecAdapter;
import com.zzusedating.androidapp.customlayout.TitleBarLayout;
import com.zzusedating.androidapp.tools.ConstantsTools;
import com.zzusedating.androidapp.tools.MyApplication;
import com.zzusedating.androidapp.model.RecommendItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class RecommendFragment extends Fragment {
    private static final String TAG = "RecommendFragment";

    private static final int NOT_LOGIN_I = 151;
    private static final int GET_DATA_SUCCESS = 150;

    private static final String NOT_LOGIN_ = "用户未登录";

    private Callback getListCallback;
    private Handler handler;

    private ArrayList<RecommendItem> recommendItems = new ArrayList<>();
    private RecyclerView recyclerView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend_layout, container, false);
        init();

        MyApplication.getClient().newCall(new Request.Builder()
                .get()
                .url(ConstantsTools.GET_RECOMMEND)
                .build()
        ).enqueue(getListCallback);

        TitleBarLayout titleBarLayout = view.findViewById(R.id.FragRecommend_TitleBar);
        titleBarLayout.setClickListenerTo(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), SpecSearchActivity.class));
            }
        }, 1);
        recyclerView = view.findViewById(R.id.FragRecommend_RecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(
                getContext(), LinearLayoutManager.VERTICAL, false)
        );
        recyclerView.setAdapter(new RecommendRecAdapter(recommendItems, getActivity()));
        return view;
    }
    private void init(){
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what){
                    case NOT_LOGIN_I:
                        MyApplication.Toast(NOT_LOGIN_);
                        break;
                    case GET_DATA_SUCCESS:
                        Objects.requireNonNull(recyclerView.getAdapter()).notifyDataSetChanged();
                        break;
                    case ConstantsTools.NETWORK_ERROR_I:
                        MyApplication.Toast(ConstantsTools.NETWORK_ERROR_);
                        break;
                }
                return true;
            }
        });
        getListCallback = new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                handler.sendMessage(ConstantsTools.createMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.code() != 200){
                    Log.e(TAG, "onResponse: code: " + response.code());
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    if (jsonObject.getInt("status") == 1){
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        Gson gson = new Gson();
                        List<RecommendItem> items = gson.fromJson(jsonArray.toString(),
                                new TypeToken<List<RecommendItem>>(){}.getType());
                        recommendItems.clear();
                        recommendItems.addAll(items);
                        handler.sendMessage(ConstantsTools.createMessage(GET_DATA_SUCCESS, items));
                    }
                    else {
                        if (jsonObject.getInt("code") == -1)
                            handler.sendMessage(ConstantsTools.createMessage(NOT_LOGIN_I));
                        else
                            handler.sendMessage(ConstantsTools.createMessage());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
